package com.cherrish.demo.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Arrays;

public class ArithmeticCalculatorLogProxy {
    public ArithmeticCalculatorLogProxy(ArithmeticCalculator target) {
        this.target = target;
    }

    private ArithmeticCalculator target;
    public ArithmeticCalculator getLogProxy(){
        ArithmeticCalculator proxy = null;
        ClassLoader loader = target.getClass().getClassLoader();
        Class[] interfaces = new Class[]{ArithmeticCalculator.class};
        InvocationHandler handler = new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                System.out.println("The method "+ method.getName() + "begins with " + Arrays.asList(args));
                Object result = method.invoke(target, args);
                System.out.println("The method "+ method.getName() + "ends with " + Arrays.asList(args));

                return result;
            }
        };
        proxy = (ArithmeticCalculator) Proxy.newProxyInstance(loader,interfaces, handler);
        return proxy;
    }
}
